/*
 * Project: book
 * 
 * File Created at 2017年9月11日
 * 
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.whb.book.common.util;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

/**
 * @Type ExcelUtil.java
 * @Desc 利用开源组件POI动态导出EXCEL文档 
 * @author wanghb
 * @date 2017年9月11日 下午10:11:24
 * @version 
 */
public class ExcelUtil<T> {

    private final static String DATE_PATTERN = "yyyy-MM-dd";

    /**
     * exportExcel:(). <br/>
     * 
     * @param title
     * @param headers
     * @param dataset
     * @return
     * @since JDK 1.8
     */
    public HSSFWorkbook exportExcel(String title, String[] headers, Collection<T> dataset) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(title);
        setData(headers, dataset, workbook, sheet);
        return workbook;
    }

    /**
     * setData:(). <br/>
     * 
     * @param headers
     * @param dataset
     * @param workbook
     * @param sheet
     * @since JDK 1.8
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void setData(String[] headers, Collection<T> dataset, HSSFWorkbook workbook,
                         HSSFSheet sheet) {

        // 设置表格默认列宽度为19个字节
        sheet.setDefaultColumnWidth((short) 19);
        //生成并设置另一个样式(header样式)
        HSSFCellStyle style = createHeadStyle(workbook);
        //产生表格标题行
        HSSFRow row = creatHeader(headers, sheet, style);
        //生成并设置另一个样式(text样式)
        HSSFCellStyle style2 = createTextStyle(workbook);

        HSSFFont font3 = workbook.createFont();
        font3.setColor(HSSFColor.BLUE.index);

        // 遍历集合数据，产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            for (short i = 0; i < fields.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style2);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                    Object value = getMethod.invoke(t, new Object[] {});
                    setValue(workbook, cell, value, font3);
                } catch (Exception e) {
                }
            }
        }

    }

    /**
     * setValue:(). <br/>
     * 
     * @param workbook
     * @param cell
     * @param value
     * @param font
     * @since JDK 1.8
     */
    private static void setValue(HSSFWorkbook workbook, HSSFCell cell, Object value,
                                 HSSFFont font) {

        //判断值的类型后进行强制类型转换
        String textValue = null;
        if (value instanceof Date) {
            Date date = (Date) value;
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
            textValue = sdf.format(date);
        } else if (value == null) {
            textValue = null;
        } else {
            //其它数据类型都当作字符串简单处理
            textValue = value.toString();
        }

        //如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
        if (textValue != null) {
            Pattern p = Pattern.compile("^//d+(//.//d+)?$");
            Matcher matcher = p.matcher(textValue);
            if (matcher.matches()) {
                //是数字当作double处理
                cell.setCellValue(Double.parseDouble(textValue));
            } else {
                HSSFRichTextString richString = new HSSFRichTextString(textValue);
                richString.applyFont(font);
                cell.setCellValue(richString);
            }
        } else {
            cell.setCellValue("");
        }

    }

    /**
     * HSSFCellStyle:(). <br/>
     * 
     * @param workbook
     * @since JDK 1.8
     */
    @SuppressWarnings("deprecation")
    private static HSSFCellStyle createHeadStyle(HSSFWorkbook workbook) {
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        return style;
    }

    /**
     * creatHeader:(). <br/>
     * 
     * @param headers
     * @param sheet
     * @param style
     * @since JDK 1.8
     */
    private static HSSFRow creatHeader(String[] headers, HSSFSheet sheet, HSSFCellStyle style) {
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        return row;
    }

    /**
     * createTextStyle:(). <br/>
     * 
     * @param workbook
     * @since JDK 1.8
     */
    @SuppressWarnings("deprecation")
    private static HSSFCellStyle createTextStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        return style2;
    }

    /**
     * createTextStyle:(). <br/>
     * 
     * @param response
     * @param workbook
     * @param fileName
     * @since JDK 1.8
     */
    public static void responseExcel(HttpServletResponse response, HSSFWorkbook workbook,
                                     String fileName) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename = " + fileName + ".xls");
            OutputStream fOut = response.getOutputStream();
            workbook.write(fOut);//把文件输出到客户端浏览器里
            fOut.flush();
            fOut.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年9月11日 wanghb create
 */
